Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

358
Vistas
How to filter a JS array based on user input in such a way that user writes "Brl", and it shows Berlin (letters aren't one after another immediately)?

I have an array of cities var cities = ['Berlin', 'Bucharest', 'Paris', 'Munich', 'Amsterdam', 'Milan']; This array needs to be filtered based on the search input passed (f.e., user inputs 'm', and it shows 'Munich', 'Amsterdam', and 'Milan', then the user adds 'a' to 'm' in search input (writes 'ma'), and it shows him "Amsterdam' and 'Milan', although these letters are not one immediately after another). Moreover, I then need these letters to be highlighted in some way, so, let's say, letters 'm' & 'a' in these words are yellow.

This is what I've done so far, but it doesn't work as I need.

var input = document.querySelector("input").value.toLowerCase().trim();
document.addEventListener('input', search)

function search() {
 var filteredArray = cities.filter(x => x.toLowerCase().includes(input));
 console.log(filteredArray);//to see what I've got
}

Appreciate any help! I'm new to JavaScript. Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You might filter like this.

document.addEventListener('input', search);

const cities = ['Berlin', 'Bucharest', 'Paris', 'Munich', 'Amsterdam', 'Milan'];

function search(e) {
  const input = e.target.value.toLowerCase().trim();
  const filteredArray = cities.filter(x => {
    const c = x.toLowerCase();
    let m = 0;
    for (let l of input) {
      const i = c.substr(m).indexOf(l);
      if (i < m) return false;
      m = i;
    }
    return true;
 });
 console.log(filteredArray);//to see what I've got
}
<input>

Also, you might remember indexes to highlight matching letters.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda